package per.kongtouxu.service.Impl;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import per.kongtouxu.dao.UserDao;
import per.kongtouxu.domain.pojo.AdminLog;
import per.kongtouxu.domain.pojo.PageBean;
import per.kongtouxu.domain.pojo.User;

import java.util.List;
@Service
public class UserServiceImpl implements per.kongtouxu.service.UserService {
    @Autowired
    private AdminLogServiceImpl adminLogService;
    @Autowired
    private UserDao userDao;
    @Override
    public PageBean<User> findByPage(String account, String Tel, String email, String startTime, String endTime, int currentPage, int pageSize) {
        PageBean<User> pageBean=null;
        try {
            //1.分页类
            pageBean = new PageBean<>();
            //2.设置当前页码
            pageBean.setCurrentPage(currentPage);
            //3.设置每页显示条数
            pageBean.setPageSize(pageSize);
            //4.设置总记录条数
            int totalCount = userDao.findCountUserByPage(account,Tel,email,startTime,endTime);
            pageBean.setTotalCount(totalCount);
            //5.设置PageBean中的实体数据
            //开始的记录条数=（当前页码-1）*每页显示条数
            int start = (currentPage -1)*pageSize;
            List<User> userList = userDao.findUserByPage(account, Tel, email, startTime, endTime, new RowBounds(start, pageSize));
            pageBean.setList(userList);
            //6.设置总页数   总页数= 总记录条数/每页显示条数=0 ？ 总记录条数/每页显示条数=0 ：（总记录条数/每页显示条数=0）+1
            int totalPage = totalCount%pageSize==0 ? totalCount/pageSize : (totalCount/pageSize)+1;
            pageBean.setTotalPage(totalPage);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //7.返回
            return pageBean;
        }
    }

    @Override
    public Integer updateUserStateByAccount(String userName, Integer stateId, AdminLog adminLog) {
        Integer result = 0;
        try {
            result = userDao.updateUserStateByAccount(userName, stateId);
            //添加日志
            adminLogService.saveAdminLog(adminLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public User findUserByUP(String account, String password) {
        User user = null;
        try {
            user = userDao.findUserByUP(account,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public Integer updateUserPwdByAccount(String userName, String password, AdminLog adminLog) {
        UserDao userDao = null;
        Integer result = 0;
        try {
            result = userDao.updateUserPwdByAccount(userName,password);
            if(result>0){
                //添加日志
                adminLogService.saveAdminLog(adminLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
